package com.estar.assistsurvy.activity;

import java.util.Set;

import com.bumptech.glide.Glide;
import com.estar.assistsurvy.R;
import com.estar.assistsurvy.entity.RequestLog;
import com.estar.assistsurvy.entity.ResponseRgt;
import com.estar.assistsurvy.entity.TSRole;
import com.estar.assistsurvy.entity.User;
import com.estar.assistsurvy.thread.LoginThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.utils.SharepreferenceUtils;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.ImageView;
import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class WelcomeActivity extends InstrumentedActivity {

	private String uUID,deviceUUID,phoneNumber,password,deviceModel,deviceToken;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
//				Toast.makeText(WelcomeActivity.this, (String) msg.obj, 0).show();
				break;
				
			case 0:
				ResponseRgt login=new ResponseRgt();
				login=(ResponseRgt) msg.obj;
				
				if(login.getCode().equals("1")){
					
					User user=login.getUser();
					SharepreferenceUtils.saveUser(user);

					TSRole role=login.getRole();
					if(null!=role&&!role.equals("")){
						SharepreferenceUtils.saveRole(role);
					}
					
//					intent=new Intent(WelcomeActivity.this,MainActivity.class);
//					startActivity(intent);
//					finish();
//				}else if(login.getCode().equals("0")){
//					intent=new Intent(WelcomeActivity.this,LoginActivity.class);
//					startActivity(intent);
//					finish();
				}else if(login.getCode().equals("2")){
					ExitUtils.Unlogin(WelcomeActivity.this, login.getMessages());
				}
				break;

			default:
				break;
			}
		};
	};
	private Intent intent;
	private ImageView welcomeImg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		welcomeImg=(ImageView) findViewById(R.id.welcomeImg);
		Glide.with(this)
		.load(R.drawable.lunchimage)
		.centerCrop()
		.into(welcomeImg);
//		PgyUpdateManager.register(this);//蒲公英版本管理注册
		PgyUpdateManager.register(WelcomeActivity.this,
				   new UpdateManagerListener() {

				      @Override
				      public void onUpdateAvailable(final String result) {

				        // 将新版本信息封装到AppBean中
				        final AppBean appBean = getAppBeanFromString(result);
				        new AlertDialog.Builder(WelcomeActivity.this,AlertDialog.THEME_HOLO_LIGHT)
				            .setTitle("更新")
				            .setMessage("发现新版本，是否更新？")
				            .setPositiveButton("确定",
				                    new DialogInterface.OnClickListener() {

		                        @Override
		                        public void onClick(
		                                DialogInterface dialog,
		                                int which) {
		                            startDownloadTask(
		                            		WelcomeActivity.this,
		                                    appBean.getDownloadURL());
		                        }
		                    })
				            .setNegativeButton(
				                    "取消",new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub

											init();
										}
									}).show();
				      }

				      @Override
				      public void onNoUpdateAvailable() {
				    	  init();
				      }
				   });
		
		Log.i("wl", "Set tag and alias success"+getSharedPreferences("alias", Context.MODE_PRIVATE).getString("deviceToken", ""));
//		if(getSharedPreferences("alias", Context.MODE_PRIVATE).getString("deviceToken", "").equals("")){
			JPushInterface.setAliasAndTags(getApplicationContext(), MightypleUtil.getDeviceId(getApplicationContext()), null,mAliasCallback);

//		}
	}

	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {  
		@Override  
		public void gotResult(int code, String alias, Set<String> tags) {  
			//	        String logs ;  
			switch (code) {  
			case 0:  
				//	            logs = "Set tag and alias success";  
				//	            Log.i("wl", logs+"code--->"+code+"----alias--->"+alias);  
				// 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。  
				SharedPreferences preference=getSharedPreferences("alias", Context.MODE_PRIVATE);
				Editor editor=preference.edit();
				editor.putString("deviceToken", JPushInterface.getRegistrationID(getApplicationContext()));
				editor.commit();
				break;  
			case 6002:  

				break;  
			default:  
			}   
		}  
	}; 

	private void init(){
		JPushInterface.init(getApplicationContext());

		if(MightypleUtil.isConnected(this)){
			Log.i("wl", "userGet--->"+userGet());
			if(userGet()){
				intent=new Intent(WelcomeActivity.this, MainActivity.class);
				startActivity(intent);
				finish();
				RequestLog requestLog=new RequestLog(uUID, deviceUUID, phoneNumber, password, deviceModel, deviceToken);
				new LoginThread(WelcomeActivity.this, handler, requestLog).start();
			}else{
//				handler.postDelayed(new Runnable() {
//
//					@Override
//					public void run() {
						// TODO Auto-generated method stub
						intent=new Intent(WelcomeActivity.this, LoginActivity.class);
						startActivity(intent);
						finish();
//					}
//				}, 2000);
			}

		}else{
			new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
			.setMessage("网络未连接，请打开网络连接重新进入")
			.setPositiveButton("好的", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					intent =  new Intent(Settings.ACTION_WIRELESS_SETTINGS);
					startActivity(intent);
					finish();
				}
			})
			.setNegativeButton("退出", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					System.exit(0);
				}
			})
			.create()
			.show();
		}
	}

	private boolean userGet(){
		SharedPreferences shareGet=getSharedPreferences("user", Context.MODE_PRIVATE);
		uUID=shareGet.getString("uuid", "");
		deviceUUID=MightypleUtil.getDeviceId(WelcomeActivity.this);
		phoneNumber=shareGet.getString("phoneNumber", "");
		password=shareGet.getString("password", "");
		deviceModel="1";
		deviceToken=JPushInterface.getRegistrationID(getApplicationContext());
		Log.i("wl", "uuid--->"+uUID);
//		if(getSharedPreferences("alias", Context.MODE_PRIVATE).getString("deviceToken", "").equals("")){
		if(uUID.equals("")||uUID==null){
			return false;
		}else{
			return true;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
		JPushInterface.onResume(getApplicationContext());
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub

		super.onPause();
		JPushInterface.onPause(getApplicationContext());
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		PgyUpdateManager.unregister();
	}
	
	
}
